﻿using Dapper;
using ProTrack.IRepository;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace ProTrack.Repository
{
    public class BaseRepository : IBaseRepository
    {
        public BaseRepository(IBaseConnection baseConnection)
        {
            BaseConnection = baseConnection.GetConn();
        }

        public SqlConnection BaseConnection { get; }




        #region Async /Await 异步流

        #region

        /// <summary>
        /// 根据SQL查询所有
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Sql"></param>
        /// <returns></returns>
        public async Task<IEnumerable<T>> QueryAllAsync<T>(string Sql) where T : class
        {
            return await BaseConnection.QueryAsync<T>(Sql);
        }
        /// <summary>
        /// 根据SQL查询指定条件的数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Sql"></param>
        /// <param name="Param"></param>
        /// <returns></returns>
        public async Task<IEnumerable<T>> QueryAsync<T>(string Sql, object Param) where T : class
        {
            return await BaseConnection.QueryAsync<T>(Sql, Param);
        }

        /// <summary>
        /// 根据SQL查询指定条件的单个模型
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Sql"></param>
        /// <param name="Param"></param>
        /// <returns></returns>
        public async Task<T> QueryFirstOrDefaultAsync<T>(string Sql, object Param) where T : class
        {
            return await BaseConnection.QueryFirstOrDefaultAsync<T>(Sql, Param);
        }

        /// <summary>
        /// 根据SQL查询单个模型
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Sql"></param>
        /// <param name="Param"></param>
        /// <returns></returns>
        public async Task<T> QueryFirstOrDefaultAsync<T>(string Sql) where T : class
        {
            return await BaseConnection.QueryFirstOrDefaultAsync<T>(Sql);
        }

        /// <summary>
        /// 根据SQL获取满足条件的数量
        /// </summary>
        /// <param name="Sql"></param>
        /// <param name="Param"></param>
        /// <returns></returns>
        public async Task<int> GetRecoreCountAsync(string Sql, object Param)
        {
            var count = Convert.ToInt32(await BaseConnection.ExecuteScalarAsync(Sql, Param));
            return count;
        }

        /// <summary>
        /// 根据SQL获取所有数量
        /// </summary>
        /// <param name="Sql"></param>
        /// <param name="Param"></param>
        /// <returns></returns>
        public async Task<int> GetRecoreCountAsync(string Sql)
        {
            var count = Convert.ToInt32(await BaseConnection.ExecuteScalarAsync(Sql));
            return count;
        }

        /// <summary>
        /// 根据SQL获取满足条件的第一行第一列数据
        /// </summary>
        /// <param name="Sql"></param>
        /// <param name="Param"></param>
        /// <returns></returns>
        public async Task<object> GetRecoreAsync(string Sql, object Param)
        {
            var obj = await BaseConnection.ExecuteScalarAsync(Sql, Param);
            return obj;
        }

        /// <summary>
        /// 根据SQL获取第一行第一列数据
        /// </summary>
        /// <param name="Sql"></param>
        /// <param name="Param"></param>
        /// <returns></returns>
        public async Task<object> GetRecoreAsync(string Sql)
        {
            var obj = await BaseConnection.ExecuteScalarAsync(Sql);
            return obj;
        }
        #endregion



        #region 新增数据

        /// <summary>
        /// 插入数据
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="model">模型</param>
        /// <param name="FieldName">Id字段名称</param>
        /// <param name="IsIdentity">是否为自增列</param>
        /// <returns></returns>
        public async Task<bool> InsertAsync<T>(T model, string FieldName = "Id", bool IsIdentity = true) where T : class
        {
            var type = model.GetType();

            var Field = string.Join(',', type.GetProperties().Select(p => p.Name));
            var Values = string.Join(',', type.GetProperties().Select(p => "@" + p.Name));

            if (IsIdentity)
            {
                //剔除Id 
                Field = Field.Substring(Field.IndexOf(FieldName + ",") + (FieldName.Length + 1));
                Values = Values.Substring(Values.IndexOf($"@{FieldName},") + (FieldName.Length + 2));
            }
            string Sql = $"Insert into {type.Name}({Field}) values ({Values})";

            return await BaseConnection.ExecuteAsync(Sql, model) > 0;
        }


        /// <summary>
        /// 插入数据，返回自增列ID
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="model">模型</param>
        /// <param name="FieldName">Id字段名称</param>
        /// <returns></returns>
        public async Task<int> InsertReturnIdAsync<T>(T model, string FieldName = "Id") where T : class
        {
            var type = model.GetType();

            var Field = string.Join(',', type.GetProperties().Select(p => p.Name));
            var Values = string.Join(',', type.GetProperties().Select(p => "@" + p.Name));

            //剔除Id 
            Field = Field.Substring(Field.IndexOf(FieldName + ",") + (FieldName.Length + 1));
            Values = Values.Substring(Values.IndexOf($"@{FieldName},") + (FieldName.Length + 2));

            string Sql = $"Insert into {type.Name}({Field}) values ({Values});select @@Identity;";

            var result = await BaseConnection.ExecuteScalarAsync(Sql, model);
            return Convert.ToInt32(result);
        }

        /// <summary>
        /// 批量插入数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list">数据集合</param>
        /// <param name="FieldName">Id字段名称</param>
        /// <param name="IsIdentity">是否为自增列</param>
        /// <returns></returns>
        public async Task<bool> InsertAsync<T>(IEnumerable<T> list, string FieldName = "Id", bool IsIdentity = true) where T : class
        {
            var type = list.First().GetType();

            var Field = string.Join(',', type.GetProperties().Select(p => p.Name));
            var Values = string.Join(',', type.GetProperties().Select(p => "@" + p.Name));

            if (IsIdentity)
            {
                //剔除Id 
                Field = Field.Substring(Field.IndexOf(FieldName + ",") + (FieldName.Length + 1));
                Values = Values.Substring(Values.IndexOf($"@{FieldName},") + (FieldName.Length + 2));
            }
            string Sql = $"Insert into {type.Name}({Field}) values ({Values})";

            return await BaseConnection.ExecuteAsync(Sql, list) > 0;
        }



        /// <summary>
        /// 关联式插入数据，主表模型，从表集合 批量插入
        /// </summary>
        /// <typeparam name="T">主表</typeparam>
        /// <typeparam name="T2">从表</typeparam>
        /// <param name="model">主表模型</param>
        /// <param name="list">从表集合</param>
        /// <returns></returns>
        public async Task<bool> InsertTranAsync<T, T2>(T model, IEnumerable<T2> list) where T : class
        {
            if (BaseConnection.State != ConnectionState.Open)
            {
                BaseConnection.Open();
            }
            using (IDbTransaction tran = BaseConnection.BeginTransaction())
            {
                try
                {

                    // Model 1
                    var type = model.GetType();

                    var Field = string.Join(',', type.GetProperties().Select(p => p.Name));
                    var Values = string.Join(',', type.GetProperties().Select(p => "@" + p.Name));
                    string Sql = $"Insert into {type.Name}({Field}) values ({Values})";

                    //Insert To Model
                    await BaseConnection.ExecuteAsync(Sql, model, tran);




                    //List Children
                    if (list.Count() > 0)
                    {
                        var t_type = list.FirstOrDefault().GetType();

                        var t_Field = string.Join(',', t_type.GetProperties().Select(p => p.Name));
                        var t_Values = string.Join(',', t_type.GetProperties().Select(p => "@" + p.Name));
                        string TModelSql = $"Insert into {t_type.Name}({t_Field}) values ({t_Values})";

                        //Insert To Model
                        await BaseConnection.ExecuteAsync(TModelSql, list, tran);
                    }





                    tran.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    //此处应当日志记录
                    tran.Rollback();
                    throw ex;
                }
            }
        }


        /// <summary>
        /// 关联式插入数据，主表模型，从表集合 批量插入【主表主键为自增】
        /// </summary>
        /// <typeparam name="T">主表</typeparam>
        /// <typeparam name="T2">从表</typeparam>
        /// <param name="model">主表模型</param>
        /// <param name="list">从表集合</param>
        /// <param name="FieldName">主键名称，默认 Id</param>
        /// <param name="InnerFieldName">从表关联字段（表2关联表1的字段）</param>
        /// <returns></returns>
        public async Task<bool> InsertIdentityTranAsync<T, T2>(T model, IEnumerable<T2> list, string FieldName = "Id", string InnerFieldName = "Default") where T : class
        {
            if (BaseConnection.State != ConnectionState.Open)
            {
                BaseConnection.Open();
            }
            using (IDbTransaction tran = BaseConnection.BeginTransaction())
            {
                try
                {

                    // 主表 模型
                    var type = model.GetType();

                    var Field = string.Join(',', type.GetProperties().Select(p => p.Name));
                    var Values = string.Join(',', type.GetProperties().Select(p => "@" + p.Name));
                    //剔除Id 
                    Field = Field.Substring(Field.IndexOf(FieldName + ",") + (FieldName.Length + 1));
                    Values = Values.Substring(Values.IndexOf($"@{FieldName},") + (FieldName.Length + 2));

                    string Sql = $"Insert into {type.Name}({Field}) values ({Values});Select @@Identity;";

                    //插入主表，获取自增列Id
                    var Id = await BaseConnection.ExecuteScalarAsync(Sql, model, tran);




                    //从表集合处理
                    if (list.Count() > 0)
                    {
                        var t_type = list.FirstOrDefault().GetType();


                        var t_Field = string.Join(',', t_type.GetProperties().Select(p => p.Name));
                        var t_Values = string.Join(',', t_type.GetProperties().Select(p => "@" + p.Name));

                        //剔除Id 
                        t_Field = t_Field.Substring(t_Field.IndexOf(FieldName + ",") + (FieldName.Length + 1));
                        t_Values = t_Values.Substring(t_Values.IndexOf($"@{FieldName},") + (FieldName.Length + 2));

                        string TModelSql = $"Insert into {t_type.Name}({t_Field}) values ({t_Values})";

                        //默认 则由主表名称+Id
                        //例如：SalesOrder  和 SalesOrderItem，则在SalesOrderItem表中关联SalesOrder 的字段为 ： SalesOrderId
                        if (InnerFieldName.Equals("Default"))
                        {
                            InnerFieldName = type.Name + "Id";
                        }

                        //处理关联数据，将从表关联字段的值 设置成主表的值
                        foreach (var item in list)
                        {
                            var types = item.GetType();


                            //找到当前从表所关联主表的字段 并赋值
                            var props = types.GetProperties().FirstOrDefault(x=>x.Name.Equals(InnerFieldName));
                            if (props != null)
                            {
                                props.SetValue(item, Convert.ToInt64(Id));
                            }
                        }

                        //Insert To Model
                        await BaseConnection.ExecuteAsync(TModelSql, list, tran);
                    }





                    tran.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    //此处应当日志记录
                    tran.Rollback();
                    throw ex;
                }
            }
        }

        public async Task<bool> InsertTranAsync<T, T2, T3>(T model, IEnumerable<T2> list, IEnumerable<T3> T3List, string FieldName = "Id", bool IsIdentity = true) where T : class
        {
            if (BaseConnection.State != ConnectionState.Open)
            {
                BaseConnection.Open();
            }
            using (IDbTransaction tran = BaseConnection.BeginTransaction())
            {
                try
                {

                    // Model 1
                    var type = model.GetType();

                    var Field = string.Join(',', type.GetProperties().Select(p => p.Name));
                    var Values = string.Join(',', type.GetProperties().Select(p => "@" + p.Name));
                    if (IsIdentity)
                    {
                        //剔除Id 
                        Field = Field.Substring(Field.IndexOf(FieldName + ",") + (FieldName.Length + 1));
                        Values = Values.Substring(Values.IndexOf($"@{FieldName},") + (FieldName.Length + 2));
                    }
                    string Sql = $"Insert into {type.Name}({Field}) values ({Values})";


                    //Insert To Model
                    await BaseConnection.ExecuteAsync(Sql, model, tran);




                    //List Children
                    if (list.Count() > 0)
                    {
                        var t_type = list.FirstOrDefault().GetType();

                        var t_Field = string.Join(',', t_type.GetProperties().Select(p => p.Name));
                        var t_Values = string.Join(',', t_type.GetProperties().Select(p => "@" + p.Name));
                        if (IsIdentity)
                        {
                            //剔除Id 
                            t_Values = t_Values.Substring(t_Values.IndexOf(FieldName + ",") + (FieldName.Length + 1));
                            t_Values = t_Values.Substring(t_Values.IndexOf($"@{FieldName},") + (FieldName.Length + 2));
                        }

                        string TModelSql = $"Insert into {t_type.Name}({t_Field}) values ({t_Values})";


                        //Insert To Model
                        await BaseConnection.ExecuteAsync(TModelSql, list, tran);
                    }

                    if (T3List.Count() > 0)
                    {
                        var t_type = T3List.FirstOrDefault().GetType();

                        var t_Field = string.Join(',', t_type.GetProperties().Select(p => p.Name));
                        var t_Values = string.Join(',', t_type.GetProperties().Select(p => "@" + p.Name));
                        if (IsIdentity)
                        {
                            //剔除Id 
                            t_Field = t_Field.Substring(t_Field.IndexOf(FieldName + ",") + (FieldName.Length + 1));
                            t_Values = t_Values.Substring(t_Values.IndexOf($"@{FieldName},") + (FieldName.Length + 2));
                        }

                        string TModelSql = $"Insert into {t_type.Name}({t_Field}) values ({t_Values})";


                        //Insert To Model
                        await BaseConnection.ExecuteAsync(TModelSql, T3List, tran);
                    }




                    tran.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    //此处应当日志记录
                    tran.Rollback();
                    throw ex;
                }
            }
        }


        public async Task<bool> InsertIdentityTranAsync<T, T2,T3>(T model, IEnumerable<T2> list, IEnumerable<T3> list2, string FieldName = "Id", string InnerFieldName = "Default") where T : class
        {
            if (BaseConnection.State != ConnectionState.Open)
            {
                BaseConnection.Open();
            }
            using (IDbTransaction tran = BaseConnection.BeginTransaction())
            {
                try
                {

                    // 主表 模型
                    var type = model.GetType();

                    var Field = string.Join(',', type.GetProperties().Select(p => p.Name));
                    var Values = string.Join(',', type.GetProperties().Select(p => "@" + p.Name));
                    //剔除Id 
                    Field = Field.Substring(Field.IndexOf(FieldName + ",") + (FieldName.Length + 1));
                    Values = Values.Substring(Values.IndexOf($"@{FieldName},") + (FieldName.Length + 2));

                    string Sql = $"Insert into {type.Name}({Field}) values ({Values});Select @@Identity;";

                    //插入主表，获取自增列Id
                    var Id = await BaseConnection.ExecuteScalarAsync(Sql, model, tran);




                    //从表集合处理
                    if (list.Count() > 0)
                    {
                        var t_type = list.FirstOrDefault().GetType();


                        var t_Field = string.Join(',', t_type.GetProperties().Select(p => p.Name));
                        var t_Values = string.Join(',', t_type.GetProperties().Select(p => "@" + p.Name));

                        //剔除Id 
                        t_Field = t_Field.Substring(t_Field.IndexOf(FieldName + ",") + (FieldName.Length + 1));
                        t_Values = t_Values.Substring(t_Values.IndexOf($"@{FieldName},") + (FieldName.Length + 2));

                        string TModelSql = $"Insert into {t_type.Name}({t_Field}) values ({t_Values})";

                        //默认 则由主表名称+Id
                        //例如：SalesOrder  和 SalesOrderItem，则在SalesOrderItem表中关联SalesOrder 的字段为 ： SalesOrderId
                        if (InnerFieldName.Equals("Default"))
                        {
                            InnerFieldName = type.Name + "Id";
                        }

                        //处理关联数据，将从表关联字段的值 设置成主表的值
                        foreach (var item in list)
                        {
                            var types = item.GetType();


                            //找到当前从表所关联主表的字段 并赋值
                            var props = types.GetProperties().FirstOrDefault(x => x.Name.Equals(InnerFieldName));
                            if (props != null)
                            {
                                props.SetValue(item, Convert.ToInt64(Id));
                            }
                        }

                        //Insert To Model
                        await BaseConnection.ExecuteAsync(TModelSql, list, tran);
                    }

                    if (list2.Count() > 0)
                    {
                        var t_type = list2.FirstOrDefault().GetType();


                        var t_Field = string.Join(',', t_type.GetProperties().Select(p => p.Name));
                        var t_Values = string.Join(',', t_type.GetProperties().Select(p => "@" + p.Name));

                        //剔除Id 
                        t_Field = t_Field.Substring(t_Field.IndexOf(FieldName + ",") + (FieldName.Length + 1));
                        t_Values = t_Values.Substring(t_Values.IndexOf($"@{FieldName},") + (FieldName.Length + 2));

                        string TModelSql = $"Insert into {t_type.Name}({t_Field}) values ({t_Values})";

                        //默认 则由主表名称+Id
                        //例如：SalesOrder  和 SalesOrderItem，则在SalesOrderItem表中关联SalesOrder 的字段为 ： SalesOrderId
                        if (InnerFieldName.Equals("Default"))
                        {
                            InnerFieldName = type.Name + "Id";
                        }

                        //处理关联数据，将从表关联字段的值 设置成主表的值
                        foreach (var item in list2)
                        {
                            var types = item.GetType();


                            //找到当前从表所关联主表的字段 并赋值
                            var props = types.GetProperties().FirstOrDefault(x => x.Name.Equals(InnerFieldName));
                            if (props != null)
                            {
                                props.SetValue(item, Convert.ToInt64(Id));
                            }
                        }

                        //Insert To Model
                        await BaseConnection.ExecuteAsync(TModelSql, list2, tran);
                    }





                    tran.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    //此处应当日志记录
                    tran.Rollback();
                    throw ex;
                }
            }
        }

        #endregion


        #region 删除数据

        /// <summary>
        /// 根据模型删除数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<bool> DeleteAsync<T>(T model) where T : class
        {
            string Sql = $"Delete {model.GetType().Name} where Id=@Id";

            return await BaseConnection.ExecuteAsync(Sql, model) > 0;
        }

        /// <summary>
        /// 根据集合批量删除
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public async Task<bool> DeleteAsync<T>(IEnumerable<T> list) where T : class
        {
            string Sql = $"Delete {list.First().GetType().Name} where Id=@Id";

            return await BaseConnection.ExecuteAsync(Sql, list) > 0;
        }

        /// <summary>
        /// 根据SQL删除指定条件的数据
        /// </summary>
        /// <param name="Sql"></param>
        /// <param name="Param"></param>
        /// <returns></returns>
        public async Task<bool> DeleteAsync(string Sql, object Param)
        {
            return await BaseConnection.ExecuteAsync(Sql, Param) > 0;
        }
        #endregion


        #region 修改数据
        public async Task<bool> UpdateAsync(string sql, object Param)
        {
            var result = await BaseConnection.ExecuteAsync(sql, Param);

            return result > 0;
        }
        public async Task<bool> UpdateTranAsync(string sql, object Param)
        {
            if (BaseConnection.State != ConnectionState.Open)
            {
                BaseConnection.Open();
            }
            using (IDbTransaction tran = BaseConnection.BeginTransaction())
            {
                try
                {
                    var result = await BaseConnection.ExecuteAsync(sql, Param, tran);
                    if (result > 0)
                    {
                        tran.Commit();
                    }
                    else
                    {
                        tran.Rollback();
                    }
                    return result > 0;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                }
                return false;
            }
        }
        public async Task<bool> UpdateAsync<T>(T model) where T : class
        {
            var type = model.GetType();

            var Field = string.Join(',', type.GetProperties().Select(p => $"{p.Name}=@{p.Name}"));
            //剔除Id
            Field = Field.Replace("Id=@Id,", "");
            string sql = $"update {type.Name} set {Field}  where Id=@Id";

            var result = await BaseConnection.ExecuteAsync(sql, model);

            return result > 0;
        }

        public async Task<bool> UpdateTranAsync<T, T2>(T model, IEnumerable<T2> list,string InnerFieldName="Default") where T : class
        {
            if (BaseConnection.State != ConnectionState.Open)
            {
                BaseConnection.Open();
            }
            using (IDbTransaction tran = BaseConnection.BeginTransaction())
            {
                try
                {

                    //主表 Model
                    var type = model.GetType();
                    var modelName = type.Name;

                    var Field = string.Join(',', type.GetProperties().Select(p => $"{p.Name}=@{p.Name}"));
                    //剔除Id
                    Field = Field.Replace("Id=@Id,", "");
                    string Sql = $"update {type.Name} set {Field}  where Id=@Id";

                    //Update To Model 
                    //更新Model
                    await BaseConnection.ExecuteAsync(Sql, model, tran);



                    if (InnerFieldName.Equals("Default"))
                    {
                        InnerFieldName = modelName + "Id";
                    }

                    //清除该单据所有子项数据 在进行新增
                    string tabName = typeof(T2).Name;
                    //此处拼接：假如SalesOrder 为主表 SalesOrderItem 从表 则 删除主表所关联从表中的数据，利用SalesOrderId 主表编号
                    string delSql = $"Delete {tabName} where {InnerFieldName}=@{InnerFieldName}";
                    await BaseConnection.ExecuteAsync(delSql, model, tran);


                    //执行新增
                    if (list.Count() > 0)
                    {
                        var t_type = list.First().GetType();
                        var t_Field = string.Join(',', t_type.GetProperties().Select(p => p.Name));
                        var t_Values = string.Join(',', t_type.GetProperties().Select(p => "@" + p.Name));
                        string addSql = $"Insert into {t_type.Name}({t_Field}) values ({t_Values})";

                        await BaseConnection.ExecuteAsync(addSql, list, tran);
                    }




                    tran.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    //此处应当日志记录
                    tran.Rollback();
                    return false;
                }
            }
        }



        public async Task<bool> UpdateIdentityTranAsync<T, T2>(T model, IEnumerable<T2> list, string FieldName="Id",string InnerFieldName = "Default",string MasterInnerFieldName="Id") where T : class
        {
            if (BaseConnection.State != ConnectionState.Open)
            {
                BaseConnection.Open();
            }
            using (IDbTransaction tran = BaseConnection.BeginTransaction())
            {
                try
                {

                    //主表 Model
                    var type = model.GetType();
                    var modelName = type.Name;

                    var Field = string.Join(',', type.GetProperties().Select(p => $"{p.Name}=@{p.Name}"));
                    //剔除Id
                    Field = Field.Replace("Id=@Id,", "");
                    string Sql = $"update {type.Name} set {Field}  where Id=@Id";

                    //Update To Model 
                    //更新Model
                    await BaseConnection.ExecuteAsync(Sql, model, tran);



                    if (InnerFieldName.Equals("Default"))
                    {
                        InnerFieldName = modelName + "Id";
                    }

                    //清除该单据所有子项数据 在进行新增
                    string tabName = typeof(T2).Name;
                    //此处拼接：假如SalesOrder 为主表 SalesOrderItem 从表 则 删除主表所关联从表中的数据，利用SalesOrderId 主表编号
                    string delSql = $"Delete {tabName} where {InnerFieldName}=@{MasterInnerFieldName}";
                    await BaseConnection.ExecuteAsync(delSql, model, tran);


                    //执行新增
                    if (list.Count() > 0)
                    {
                        var t_type = list.First().GetType();
                        var t_Field = string.Join(',', t_type.GetProperties().Select(p => p.Name));
                        var t_Values = string.Join(',', t_type.GetProperties().Select(p => "@" + p.Name));
                        //剔除Id 
                        t_Field = t_Field.Substring(t_Field.IndexOf(FieldName + ",") + (FieldName.Length + 1));
                        t_Values = t_Values.Substring(t_Values.IndexOf($"@{FieldName},") + (FieldName.Length + 2));
                        string addSql = $"Insert into {t_type.Name}({t_Field}) values ({t_Values})";


                        await BaseConnection.ExecuteAsync(addSql, list, tran);
                    }




                    tran.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    //此处应当日志记录
                    tran.Rollback();
                    return false;
                }
            }
        }

        public async Task<bool> UpdateIdentityTranAsync<T, T2,T3>(T model, IEnumerable<T2> list, IEnumerable<T3> list2, string FieldName = "Id", string InnerFieldName = "Default", string MasterInnerFieldName = "Id") where T : class
        {
            if (BaseConnection.State != ConnectionState.Open)
            {
                BaseConnection.Open();
            }
            using (IDbTransaction tran = BaseConnection.BeginTransaction())
            {
                try
                {

                    //主表 Model
                    var type = model.GetType();
                    var modelName = type.Name;

                    var Field = string.Join(',', type.GetProperties().Select(p => $"{p.Name}=@{p.Name}"));
                    //剔除Id
                    Field = Field.Replace("Id=@Id,", "");
                    string Sql = $"update {type.Name} set {Field}  where Id=@Id";

                    //Update To Model 
                    //更新Model
                    await BaseConnection.ExecuteAsync(Sql, model, tran);



                    //从表操作
                    {

                        if (InnerFieldName.Equals("Default"))
                        {
                            InnerFieldName = modelName + "Id";
                        }

                        //清除该单据所有子项数据 在进行新增
                        string tabName = typeof(T2).Name;
                        //此处拼接：假如SalesOrder 为主表 SalesOrderItem 从表 则 删除主表所关联从表中的数据，利用SalesOrderId 主表编号
                        string delSql = $"Delete {tabName} where {InnerFieldName}=@{MasterInnerFieldName}";
                        await BaseConnection.ExecuteAsync(delSql, model, tran);


                        //执行新增
                        if (list.Count() > 0)
                        {
                            var t_type = list.First().GetType();
                            var t_Field = string.Join(',', t_type.GetProperties().Select(p => p.Name));
                            var t_Values = string.Join(',', t_type.GetProperties().Select(p => "@" + p.Name));
                            //剔除Id 
                            t_Field = t_Field.Substring(t_Field.IndexOf(FieldName + ",") + (FieldName.Length + 1));
                            t_Values = t_Values.Substring(t_Values.IndexOf($"@{FieldName},") + (FieldName.Length + 2));
                            string addSql = $"Insert into {t_type.Name}({t_Field}) values ({t_Values})";

                            await BaseConnection.ExecuteAsync(addSql, list, tran);
                        }
                    }
                    //从表操作
                    {

                        if (InnerFieldName.Equals("Default"))
                        {
                            InnerFieldName = modelName + "Id";
                        }

                        //清除该单据所有子项数据 在进行新增
                        string tabName = typeof(T3).Name;
                        //此处拼接：假如SalesOrder 为主表 SalesOrderItem 从表 则 删除主表所关联从表中的数据，利用SalesOrderId 主表编号
                        string delSql = $"Delete {tabName} where {InnerFieldName}=@{MasterInnerFieldName}";
                        await BaseConnection.ExecuteAsync(delSql, model, tran);


                        //执行新增
                        if (list2.Count() > 0)
                        {
                            var t_type = list2.First().GetType();
                            var t_Field = string.Join(',', t_type.GetProperties().Select(p => p.Name));
                            var t_Values = string.Join(',', t_type.GetProperties().Select(p => "@" + p.Name));
                            //剔除Id 
                            t_Field = t_Field.Substring(t_Field.IndexOf(FieldName + ",") + (FieldName.Length + 1));
                            t_Values = t_Values.Substring(t_Values.IndexOf($"@{FieldName},") + (FieldName.Length + 2));
                            string addSql = $"Insert into {t_type.Name}({t_Field}) values ({t_Values})";

                            await BaseConnection.ExecuteAsync(addSql, list2, tran);
                        }
                    }




                    tran.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    //此处应当日志记录
                    tran.Rollback();
                    throw ex;
                }
            }
        }


        public async Task<bool> UpdateTranAsync<T, T2, T3>(T model, IEnumerable<T2> list, IEnumerable<T3> T3list) where T : class
        {
            if (BaseConnection.State != ConnectionState.Open)
            {
                BaseConnection.Open();
            }
            using (IDbTransaction tran = BaseConnection.BeginTransaction())
            {
                try
                {

                    //主表 Model
                    var type = model.GetType();
                    var modelName = type.Name;

                    var Field = string.Join(',', type.GetProperties().Select(p => $"{p.Name}=@{p.Name}"));
                    //剔除Id
                    Field = Field.Replace("Id=@Id,", "");
                    string Sql = $"update {type.Name} set {Field}  where Id=@Id";

                    //Update To Model 
                    //更新Model
                    await BaseConnection.ExecuteAsync(Sql, model, tran);



                    //清除该单据所有子项数据 在进行新增
                    string tabName = typeof(T2).Name;
                    string delSql = $"Delete {tabName} where {modelName}Id=@Id";
                    await BaseConnection.ExecuteAsync(delSql, model, tran);


                    //清除该单据所有子项数据 在进行新增
                    string tabName3 = typeof(T3).Name;
                    string delSql3 = $"Delete {tabName3} where {modelName}Id=@Id";
                    await BaseConnection.ExecuteAsync(delSql3, model, tran);


                    //执行新增
                    if (list.Count() > 0)
                    {
                        var t_type = list.First().GetType();
                        var t_Field = string.Join(',', t_type.GetProperties().Select(p => p.Name));
                        var t_Values = string.Join(',', t_type.GetProperties().Select(p => "@" + p.Name));
                        string addSql = $"Insert into {t_type.Name}({t_Field}) values ({t_Values})";

                        await BaseConnection.ExecuteAsync(addSql, list, tran);
                    }

                    if (T3list.Count() > 0)
                    {
                        var t_type = T3list.First().GetType();
                        var t_Field = string.Join(',', t_type.GetProperties().Select(p => p.Name));
                        var t_Values = string.Join(',', t_type.GetProperties().Select(p => "@" + p.Name));
                        string addSql = $"Insert into {t_type.Name}({t_Field}) values ({t_Values})";

                        await BaseConnection.ExecuteAsync(addSql, T3list, tran);
                    }



                    tran.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    //此处应当日志记录
                    tran.Rollback();
                    return false;
                }
            }
        }

        #endregion



        #endregion
    }
}
